// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database();
// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    let {
        groupId,
        userId,
        code
    } = event;
    if (!userId) userId = wxContext.OPENID;
    if (!code && !groupId) return {err:'缺少关键信息'}
    console.log(event);
    
    //删除code
    await db.collection('code').where({
        code,
        userId,
        group: groupId
    }).remove()

    //刷新用户项目索引
    const res = await db.collection('code').field({
        role:true,
        group:true
    }).where({userId}).get()
    const project = res.data.map(item => item.group).filter(a => a)
    const master = project.filter(a => a.role === 'master')
    await db.collection('user').doc(userId).update({
        data: {
            project: db.command.set(project),
            master: db.command.set(master)
        }
    })
    //清理用户任务
    const missions=await db.collection('mission').field({
        _id:true
    }).where({
        userId,
        projectId:groupId
    }).get()
    if(missions.data&&missions.data.length){
        await Promise.all(missions.data.map(item=>{
            return new Promise(resolve=>{
                cloud.callFunction({
                    name:'delMission',
                    data:{
                        id:item._id
                    }
                }).then(resolve)
            })
        }))
    }

    const coders = await db.collection('code').where({
        group: groupId
    }).get()

    // console.log('\n当前组成员人数:' + coders.data.length)
    if (!coders.data.length) {
        //组为空 删除组
        console.log('\n组为空，删除组')
        await Promise.all([
            db.collection('group').doc(groupId).remove().then(() => { }).catch(err => {
                console.log(err);
            }),
            db.collection('mission').where({
                projectId: groupId
            }).remove()
        ])
    }
    return 
}